import re
import xadmin

from apps.courses.models import Course,CourseResource,Lesson,Video,BannerCourse
from apps.organizations.models import Org


class LessonInline(object):
    model = Lesson
    extra = 0

class CourseResourceInline(object):
    model = CourseResource
    extra = 0

class VideoInline(object):
    model = Video
    extra = 0

"""
两个Admin对同一张表进行管理
"""
class CourseAdmin(object):
    """
    课程后台管理
    """
    list_filter = ["org", "name", "degree", "learnTimes", "students", "favNum", "clickNum", "addTime"]
    search_fields = ["name"]
    list_display = [ "name", "org", "degree", "desc", "learnTimes", "getCourseLessonNum", "getCourseResourceNum"]
    ordering = ["addTime"]
    readonly_fields = ["students","favNum","clickNum","addTime"]
    list_editable = ["name", "degree", "learnTimes", "desc"]
    relfield_style = "fk-ajax"
    inlines = [CourseResourceInline]
    # 为detail字段添加ueditor编辑功能
    style_fields = {"detail":"ueditor"}

    # 重写父类的queryset方法
    def queryset(self):
        return super(CourseAdmin,self).queryset().filter(isBanner=False)

    # 重写（课程后台管理）的save方法
    def save_model(self):
        obj = self.new_obj
        obj.save()
        if obj.org is not None:
            org = self.org
            org.courses = org.objects.filter(org=org)
            org.save()

    # 重写（课程后台管理）的delete方法
    def delete_model(self):
        obj = self.new_obj
        obj.delete()
        if obj.org is not None:
            org = self.org
            org.courses = org.objects.filter(org=org) - 1
            org.save()


class BannerCourseAdmin(object):
    """
    轮播课程后台管理
    """
    list_filter = ["org", "name", "degree", "learnTimes", "students", "favNum", "clickNum", "addTime"]
    search_fields = ["name"]
    list_display = ["name", "org", "degree", "desc", "learnTimes"]
    ordering = ["-clickNum"]
    readonly_fields = ["students", "favNum", "clickNum", "addTime"]
    relfield_style = "fk-ajax"
    inlines = [CourseResourceInline]

    def queryset(self):
        return super(BannerCourseAdmin,self).queryset().filter(isBanner=True)


class LessonAdmin(object):
    """
    课程-章节后台管理
    """
    list_display = ["course", "name", "addTime"]
    search_fields = ["name"]
    list_filter = ["course__name", "name", "addTime"]
    readonly_fields = ["addTime"]
    ordering = ["addTime"]
    relfield_style = "fk-ajax"
    inlines = [VideoInline]
    # 开启excel导入功能
    import_excel = True

    def post(self, request, *args, **kwargs):
        """
        在LessonAdmin后头模块中POST请求都会调用该方法,
        这里需要重写其post方法,添加Excel导入功能
        """
        importLesson(self,request,Lesson)
        # sqllist = []
        # import time
        # for i in range(1,10000000):
        #     sql = Lesson(name="测试"+str(i),course_id=1)
        #     sqllist.append(sql)
        #     if i%10000 == 0:
        #         Lesson.objects.bulk_create(sqllist)
        #         sqllist = []
        #         print("1000条数据添加完毕-----",time.strftime('%Y-%m-%d %H-%M-%S',time.localtime(time.time())))
        return super(LessonAdmin, self).post(request, args, kwargs)


class CourseResourceAdmin(object):
    """
    课程-资源后台管理
    """
    list_display = ["course", "name", "addTime","download"]
    search_fields = ["course", "name","download"]
    list_filter = ["course__name", "name", "addTime","download"]
    readonly_fields = ["addTime"]


class VideoAdmin(object):
    """
    章节-视频后台管理
    """
    list_display = ["lesson", "name", "urlAddress", "addTime"]
    search_fields = ["name"]
    list_filter = ["lesson__name", "name", "addTime"]
    readonly_fields = ["addTime"]


xadmin.site.register(Course,CourseAdmin)
xadmin.site.register(BannerCourse,BannerCourseAdmin)
xadmin.site.register(Lesson,LessonAdmin)
xadmin.site.register(CourseResource,CourseResourceAdmin)
xadmin.site.register(Video,VideoAdmin)


def importLesson(self,request,Lesson):
    """
    读取Excel文件信息: Excel 2003-用xlrd,Excel 2007+用openpyxl
    """
    if request.FILES:
        objlist = []
        sqllist = []
        headers = ["course", "name"]
        excelFile = request.FILES["excelFile"]
        # xlsx
        # 获取默认选中的worksheet
        # worksheet = workbook.active
        # for row in worksheet.rows:
        #     for cell in row:
        #         print(cell.value)
        if re.compile(".*\.xlsx").match(excelFile.name):
            from openpyxl import load_workbook
            # excel文件对象
            workbook = load_workbook(filename=excelFile, read_only=True)
            # print("Worksheet name(s):", workbook.get_sheet_names())
            # 遍历所有worksheet
            for worksheet in workbook:
                # print("title:",worksheet.title)
                max_column = worksheet.max_column
                if max_column < len(headers):
                    break
                max_row = worksheet.max_row
                # 遍历所有worksheet.rows
                for i in range(2, max_row + 1):
                    # print(worksheet.cell(row=i, column=1).value)
                    temp = {}
                    # 遍历所有worksheet.rows.colums
                    for j in range(1, len(headers) + 1):
                        temp[headers[j-1]] = worksheet.cell(row=i,column=j).value
                    objlist.append(temp)
                # 每一worksheet读取完毕执行一次添加操作
                for obj in objlist:
                    course = obj["course"]
                    name = obj["name"]
                    # 过滤和去重复操作
                    courseObj = Course.objects.filter(name=course)
                    lessonObj = Lesson.objects.filter(name=name)
                    if courseObj and not lessonObj:
                        sql = Lesson(course=courseObj[0],name=name)
                        sqllist.append(sql)
                Lesson.objects.bulk_create(sqllist)
                # 清空参数
                objlist = []
                sqllist = []
        # xls
        elif re.compile(".*\.xls").match(excelFile.name):
            import xlrd
            workbook = xlrd.open_workbook(file_contents=excelFile.read())
            # sheet2 = workbook.sheet_by_index(1)
            # sheet2 = workbook.sheet_by_name('sheet2')
            for sheetName in workbook.sheet_names():
                worksheet = workbook.sheet_by_name(sheetName)
                #print(worksheet.name)
                # rows = worksheet.row_values(0)
                # cols = worksheet.col_values(0)
                max_column = worksheet.ncols
                if max_column < len(headers):
                    break
                max_row = worksheet.nrows
                # 遍历所有worksheet.rows
                for i in range(1, max_row):
                    temp = {}
                    # 遍历所有worksheet.rows.colums
                    # sheet.cell(1, 0).value.encode('utf-8')
                    # sheet.cell_value(1, 0).encode('utf-8')
                    # sheet.row(1)[0].value.encode('utf-8')
                    for j in range(0, len(headers)):
                        temp[headers[j]] = worksheet.cell(i,j).value.encode('utf-8')
                    objlist.append(temp)
                # 每一worksheet读取完毕执行一次添加操作
                for obj in objlist:
                    course = obj["course"]
                    name = obj["name"]
                    # 过滤和去重复操作
                    courseObj = Course.objects.filter(name=course)
                    lessonObj = Lesson.objects.filter(name=name)
                    if courseObj and not lessonObj:
                        sql = Lesson(course=courseObj[0], name=name)
                        sqllist.append(sql)
                Lesson.objects.bulk_create(sqllist)
                # 清空参数
                objlist = []
                sqllist = []
        # 非法处理
        else:
            pass
